<?php

namespace app\api\controller\v1\untils;

use app\api\controller\Api;

class Sms extends Api
{

    public function send(){
        $rule = [
            'phone'    => 'require|mobile',
        ];
        $message  =   [
            'phone.require' => '手机号不为空',
            'phone.mobile' => '手机号错误',
        ];

       $this->validate($this->post, $rule,$message);

        $time = 60;
        // 生成验证码
        $code = mt_rand(100000, 999999);

        $this->sms_lock($this->post);
        $this->ip_lock($this->request->ip());
        // 将验证码保存到session中，以便稍后验证
//        if(!empty( cache('sms_code_'.$data['phone'])))$this->error('发送失败,请一分钟后再发');
        cache('sms_code_'.$this->post['phone'], $code,$time);
        // 发送短信的代码（使用第三方SDK发送短信）
        $result = true;
        if ($result) {
           $this->success('发送成功',['code'=>$code,'time'=>$time]);
        } else {
           $this->error('发送失败');
        }
    }

    /**
     * 验证短信
     * @param $code
     * @param $phone
     * @return bool
     */
     public static function checkVerifyCode($code, $phone){
        if(cache('sms_code_'.$phone) === $code){
            return true;
        }else{
            return false;
        }

     }


     private function sms_lock($data){
         if(cache('sms_lock_'.$data['phone'])>=10) $this->error('手机号验证码发送超限');
         if(empty(cache('sms_lock_'.$data['phone']))){
             cache('sms_lock_'.$data['phone'],1);
         }else{
             cache('sms_lock_'.$data['phone'],cache('sms_lock_'.$data['phone'])+1);

         }

     }
     private function ip_lock($data){
         if(cache('ip_lock_'.$data)>=100) $this->error('当前网络验证码发送超限');
         if(empty(cache('ip_lock'.$data))){
             cache('ip_lock_'.$data,1);
         }else{
             cache('ip_lock_'.$data,cache('ip_lock_'.$data)+1);
         }
     }



}